from typing import Optional, List, Dict, Any
from datetime import datetime
from app.utils.log_config import get_logger
from app.models.base import Model

logger = get_logger('inventory')

class Inventory(Model):
    """
    库存模型
    """
    # 表名
    table_name = "inventory"
    # 主键
    primary_key = "id"
    
    def __init__(self, id=None, product_name=None, product_id=None, quantity=0, warehouse=None, update_time=None):
        super().__init__(
            id=id,
            product_name=product_name,
            product_id=product_id,
            quantity=quantity,
            warehouse=warehouse,
            update_time=update_time
        )
    
    @classmethod
    def _tuple_to_instance(cls, row: tuple) -> 'Inventory':
        """
        从元组创建实例
        """
        return cls(
            id=row[0],
            product_name=row[1],
            product_id=row[2],
            quantity=row[3],
            warehouse=row[4],
            update_time=row[5] if len(row) > 5 else None
        )
    
    @classmethod
    def find_by_product_id(cls, product_id: str, warehouse: Optional[str] = None) -> Optional['Inventory']:
        """
        根据产品ID和仓库查找库存
        """
        filters = {'product_id': product_id}
        if warehouse:
            filters['warehouse'] = warehouse
        
        results = cls.find_all(**filters)
        return results[0] if results else None
    
    def update_quantity(self, change_amount: int) -> bool:
        """
        更新库存数量
        
        Args:
            change_amount: 变更数量（正数为增加，负数为减少）
            
        Returns:
            bool: 更新是否成功
        """
        # 检查库存是否足够（如果是减少）
        if change_amount < 0 and self.quantity < abs(change_amount):
            logger.warning(f"库存不足: {self.product_name} 当前: {self.quantity}, 需要: {-change_amount}")
            return False
        
        try:
            self.quantity += change_amount
            self.update_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            return self.save()
        except Exception as e:
            logger.error(f"更新库存失败: {e}")
            return False
    
    def to_dict(self) -> Dict[str, Any]:
        """
        转换为字典
        """
        result = super().to_dict()
        # 确保数量是整数
        if 'quantity' in result:
            result['quantity'] = int(result['quantity'])
        return result

class StockDoc(Model):
    """
    出入库单据模型
    """
    table_name = "stock_doc"
    primary_key = "doc_id"
    
    def __init__(self, doc_id=None, doc_type=None, warehouse=None, operator=None, create_time=None, status='已完成'):
        super().__init__(
            doc_id=doc_id,
            doc_type=doc_type,
            warehouse=warehouse,
            operator=operator,
            create_time=create_time,
            status=status
        )
    
    @classmethod
    def _tuple_to_instance(cls, row: tuple) -> 'StockDoc':
        return cls(
            doc_id=row[0],
            doc_type=row[1],
            warehouse=row[2],
            operator=row[3],
            create_time=row[4],
            status=row[5] if len(row) > 5 else '已完成'
        )

class StockDocItem(Model):
    """
    出入库单据明细模型
    """
    table_name = "stock_doc_item"
    primary_key = "id"
    
    def __init__(self, id=None, doc_id=None, product_id=None, product_name=None, quantity=0):
        super().__init__(
            id=id,
            doc_id=doc_id,
            product_id=product_id,
            product_name=product_name,
            quantity=quantity
        )
    
    @classmethod
    def _tuple_to_instance(cls, row: tuple) -> 'StockDocItem':
        return cls(
            id=row[0],
            doc_id=row[1],
            product_id=row[2],
            product_name=row[3],
            quantity=row[4]
        )